package com.example.iread.exception;

import android.content.Intent;

import androidx.annotation.NonNull;

import com.example.iread.activity.LoginActivity;
import com.example.iread.application.MyApplication;
import com.example.iread.util.ToastUtil;

public class MyCatchException implements Thread.UncaughtExceptionHandler {

    private static MyCatchException myCatchException;
    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
    private MyApplication application;

    public static MyCatchException getInstance() {
        if (myCatchException == null) myCatchException = new MyCatchException();
        return myCatchException;
    }

    public void init() {
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        if (throwable instanceof TokenExpireException) {
            ToastUtil.show(MyApplication.getInstance().getApplicationContext(), "Token has expired, please log in again");
            application = MyApplication.getInstance();
            Intent intent = new Intent(application, LoginActivity.class);
            application.startActivity(intent);
        } else if (throwable instanceof MyException) {
            // 我的异常
            ToastUtil.show(MyApplication.getInstance().getApplicationContext(), ((MyException) throwable).message);
        } else {
            defaultUncaughtExceptionHandler.uncaughtException(thread, throwable);
        }

    }
}
